<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>用户管理</title>
    <base href="<%=basePath%>">
    <%--<link rel="stylesheet" href="assets/libs/layui/css/layui.css"/>--%>
    <link rel="stylesheet" href="//unpkg.com/layui@2.6.8/dist/css/layui.css">
    <link rel="stylesheet" href="assets/module/admin.css?v=318"/>
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
        #userTable + .layui-table-view .layui-table-body tbody > tr > td {
            padding: 0;
        }
        #userTable + .layui-table-view .layui-table-body tbody > tr > td > .layui-table-cell {
            height: 48px;
            line-height: 48px;
        }
        .tb-img-circle {
            width: 40px;
            height: 40px;
            cursor: zoom-in;
            border-radius: 50%;
            border: 2px solid #dddddd;
        }
    </style>
</head>
<body>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 表格工具栏 -->
            <form class="layui-form toolbar">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">账&emsp;号:</label>
                        <div class="layui-input-inline">
                            <input name="userName" class="layui-input" placeholder="输入账号"/>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">用户名:</label>
                        <div class="layui-input-inline">
                            <input name="name" class="layui-input"  placeholder="输入用户名"/>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">性&emsp;别:</label>
                        <div class="layui-input-inline">
                            <select name="sex">
                                <option value="">选择性别</option>
                                <option value="男">男</option>
                                <option value="女">女</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">&emsp;
                        <button class="layui-btn icon-btn" lay-filter="userTbSearch" lay-submit>
                            <i class="layui-icon">&#xe615;</i>搜索
                        </button>
                    </div>
                </div>
            </form>
            <!-- 数据表格 -->
            <table id="userTable" lay-filter="userTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="userTbBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="reset">重置密码</a>
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="editRole">分配角色</a>
</script>
<!-- 表格状态列 -->
<script type="text/html" id="userTbState">
    <input type="checkbox" lay-filter="userTbStateCk" value="{{d.id}}" lay-skin="switch"
           lay-text="锁定|正常" {{d.status==0?'checked':''}} style="display: none;"/>
    <p style="display: none;">{{d.state==0?'正常':'锁定'}}</p>
</script>
<!-- 表单弹窗-新增+修改-->
<script type="text/html" id="userEditDialog">
    <form id="userEditForm" lay-filter="userEditForm" class="layui-form model-form">
        <input name="userId" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">账号:</label>
            <div class="layui-input-block">
                <input name="userName" value="monkey" id="userName" placeholder="请输入账号" class="layui-input"
                       lay-verType="tips" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">用户名:</label>
            <div class="layui-input-block">
                <input name="name" value="马超" placeholder="请输入用户名" class="layui-input"
                       lay-verType="tips" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item" id="passwordDiv">
            <label class="layui-form-label layui-form-required">密码:</label>
            <div class="layui-input-block">
                <input name="passWord" placeholder="请输入" class="layui-input"
                       lay-verType="tips" lay-verify="required" required />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">性别:</label>
            <div class="layui-input-block">
                <input type="radio" name="sex" value="男" title="男" checked/>
                <input type="radio" name="sex" value="女" title="女"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">手机号:</label>
            <div class="layui-input-block">
                <input name="phone" value="15630051326" placeholder="请输入手机号" class="layui-input"
                       lay-verType="tips" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">角色:</label>
            <div class="layui-input-block">
                <div id="userEditRoleSel"></div>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn" lay-filter="userEditSubmit" lay-submit>保存</button>
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
        </div>
    </form>
</script>
<!-- 穿梭框-->
<script type="text/html" id="ransfer">
    <div id="layDemoTransfer" style="min-width: 490px;margin-top: 40px;margin-left: 70px"></div>
    <div class="layui-form-item text-right" style="margin-right: 50px;margin-top: 20px">
        <button class="layui-btn" lay-filter="userEditSubmit" ew-event="roleToAdd">保存</button>
        <button class="layui-btn layui-btn-primary" type="button" ew-event="roleClear">取消</button>

    </div>
</script>
<!-- js部分 -->
<script type="text/javascript" src="assets/libs/layui/layui.js"></script>
<script type="text/javascript" src="assets/js/common.js?v=318"></script>
<script>
    layui.use(['layer', 'form', 'table', 'util', 'admin', 'xmSelect','transfer','laypage'], function () {
        let $ = layui.jquery;
        let layer = layui.layer;
        let form = layui.form;
        let table = layui.table;
        let util = layui.util;
        let admin = layui.admin;
        let xmSelect = layui.xmSelect;
        let transfer = layui.transfer;
        /* 渲染表格 */
        let insTb;
        insTb = table.render({
            elem: '#userTable',
            url: 'user/getUserList',
            toolbar: ['<p>',
                '<button lay-event="add" class="layui-btn layui-btn-sm icon-btn"><i class="layui-icon">&#xe654;</i>添加</button>&nbsp;',
                '<button lay-event="del" class="layui-btn layui-btn-sm layui-btn-danger icon-btn"><i class="layui-icon">&#xe640;</i>删除</button>',
                '</p>'].join(''),
            cellMinWidth: 100,
            page: true, //开启分页
            limit:5,
            limits:[5,10,20,30],
            cols: [[
                {type: 'checkbox'},
                {type: 'numbers',title: "id"},
                {field: "id",title: 'id',hide:true},
                {field: 'userName', title: '账号', sort: true,width: 100},
                {field: 'name', title: '用户名', sort: true, width: 100},
                {
                    field: 'headUrl', title: '头像', templet: function (d) {
                        let url = d.headUrl || 'assets/images/head.jpg';
                        return '<img data-index="' + (d.LAY_INDEX - 1) + '" src="' + url + '" class="tb-img-circle" tb-img alt=""/>'
                    },align: 'center', width: 90, unresize: true
                },
                {field: 'phone', title: '手机号', sort: true, width: 120},
                {
                    field: 'sysRoles', title: '角色', templet: function (d) {
                        return d.sysRoles.map(function (item) {
                            return '<span class="layui-badge layui-badge-gray">' + item.roleName + '</span>';
                        }).join('&nbsp;&nbsp;');
                    }, sort: true, width: 200
                },
                {field: 'status', title: '状态', templet: '#userTbState', sort: true, width: 100},
                {
                    field: 'createTime', title: '创建时间', templet: function (d) {
                        return util.toDateString(d.createTime);
                    }, sort: true
                },
                {
                    field: 'updateTime', title: '更新时间', templet: function (d) {
                        return util.toDateString(d.createTime);
                    }, sort: true
                },
                {title: '操作', toolbar: '#userTbBar', align: 'center', minWidth: 300}
            ]]

        });

        /* 表格搜索 */
        form.on('submit(userTbSearch)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}});
            return false;
        });

        /* 表格工具条点击事件 */
        table.on('tool(userTable)', function (obj) {
            if (obj.event === 'edit') { // 修改
                showEditModel(obj.data);
            } else if (obj.event === 'del') { // 删除
                doDel(obj);
            } else if (obj.event === 'reset') { // 重置密码
                resetPsw(obj);
            }else if(obj.event==='editRole'){
                editRole(obj);
            }
        });

        /* 表格头工具栏点击事件 */
        table.on('toolbar(userTable)', function (obj) {
            if (obj.event === 'add') { // 添加
                showEditModel();
            } else if (obj.event === 'del') { // 删除
                let checkRows = table.checkStatus('userTable');
                if (checkRows.data.length === 0) {
                    layer.msg('请选择要删除的数据', {icon: 2});
                    return;
                }
                let ids = checkRows.data.map(function (d) {
                    return d.userId;
                });
                doDel({ids: ids});
            }
        });

        /* 显示表单弹窗 */
        function showEditModel(mData) {
            let insRoleSel;
            layer.open({
                type: 1,
                title: (mData ? '修改' : '添加') + '用户',
                content: $('#userEditDialog').html(),
                area: ['600px', '480px'],
                success: function (layero, dIndex) {
                    if(mData!=undefined){
                        //密码框隐藏
                        $("#passwordDiv").hide();
                        //弹窗高度减小
                        $("#userEditForm").parent().css("height","420px");
                        $("#userEditForm").parent().parent().css("height","420px");
                        //修改设置账户名禁用
                        $("#userName").addClass("layui-disabled");
                        $("#userName").css("disabled","disabled");
                        $("#userName").css("readonly","readonly")
                    }
                    // 回显表单数据
                    form.val('userEditForm', mData);
                    //发送ajax请求渲染角色多选下拉框
                    admin.req('role/getRoleList', function(res){
                        let dataLeftRoles=res.LeftRoles;
                        let  array=new Array();
                        for (let role of dataLeftRoles) {
                            let object=new Object();
                            object.name=role.roleName;
                            object.value=role.id;
                            array.push(object);
                        }
                        //渲染角色多选下拉框
                        insRoleSel = xmSelect.render({
                            el: '#userEditRoleSel',
                            name: 'userEditRoleSel',
                            layVerify: 'required',
                            layVerType: 'tips',
                            data:array
                        });
                        // 回显选中角色
                        console.log(mData)
                        if (mData && mData.sysRoles) {
                            insRoleSel.setValue(mData.sysRoles.map(function (item) {
                                return item.id;
                            }));
                        }
                    });
                    // 禁止弹窗出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                    // 表单提交事件
                    form.on('submit(userEditSubmit)', function (data) {
                        data.field.roleIds = insRoleSel.getValue('valueStr');
                        let loadIndex = layer.load(2);
                        //修改是前-添加在后
                        $.post(mData ? 'user/updateUser' : 'user/addUser', data.field, function (res) {  // 实际项目这里url可以是mData?'user/update':'user/add'
                            layer.close(loadIndex);
                            if (res.code === 200) {
                                layer.close(dIndex);
                                layer.msg(res.message, {icon: 1});
                                //表格重载
                                insTb.reload({page: {curr: 1}});
                            } else {
                                layer.msg(res.message, {icon: 2});
                            }
                        }, 'json');
                        return false;
                    });
                }
            });
        }

        /* 删除 */
        function doDel(obj) {
            layer.confirm('确定要删除选中数据吗？', {
                //skin: 'layui-layer-admin',
                shade: .1
            }, function (i) {
                layer.close(i);
                let loadIndex = layer.load(2);
                console.log(obj.data.sysRoles)
                let ids = obj.data.sysRoles.map(function (d) {
                    return d.id;
                });
                console.log(ids);
                $.get('user/delUser', {
                    id: obj.data ? obj.data.id : '',
                    ids: ids ? ids.join(',') : ''
                }, function (res) {
                    layer.close(loadIndex);
                    console.log(res)
                    if (res.code === 200) {
                        layer.msg(res.message, {icon: 1});
                        insTb.reload({page: {curr: 1}});
                    } else {
                        layer.msg(res.message, {icon: 2});
                    }
                }, 'json');
            });
        }

        /* 修改用户状态 */
        form.on('switch(userTbStateCk)', function (obj) {
            let loadIndex = layer.load(2);
            console.log(obj.value);
            console.log(obj.elem.checked);
            $.get('user/updateUserStatus', {
                userId: obj.value,
                state: obj.elem.checked ? 0 : 1
            }, function (res) {
                layer.close(loadIndex);
                console.log(res);
                if (res.code === 200) {
                    layer.msg(res.message, {icon: 1});
                } else {
                    layer.msg(res.message, {icon: 2});
                    $(obj.elem).prop('checked', !obj.elem.checked);
                    form.render('checkbox');
                }
            }, 'json');
        });

        /* 重置密码 */
        function resetPsw(obj) {
            layer.confirm('确定要重置“' + obj.data.nickName + '”的登录密码吗？', {
                //skin: 'layui-layer-admin',
                shade: .1
            }, function (i) {
                layer.close(i);
                let loadIndex = layer.load(2);
                $.get('../../json/ok.json', {
                    userId: obj.data.userId
                }, function (res) {
                    layer.close(loadIndex);
                    if (res.code === 200) {
                        layer.msg(res.msg, {icon: 1});
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'json');
            });
        }

        /* 赋值角色 */
        function editRole(mData) {
            console.log(mData.data)
            layer.open({
                type: 1,
                title: '修改权限',
                content: $('#ransfer').html(),
                area: ['600px', '530px'],
                success: function (layero, dIndex) {
                    //获取穿梭框数据
                    admin.req('role/getRoleList', function(res){
                            let dataLeftRoles=res.LeftRoles;
                            let dataRightRoles=res.RightRoles;
                            //收集id值
                            let getIds = dataRightRoles.map(item=>item.id)
                            //重构对象结构
                            let leftData=new Array();
                            for (let ld of dataLeftRoles) {
                                leftData.push(new valueObject(ld))
                            }
                            // 穿梭框
                            transfer.render({
                                elem: '#layDemoTransfer',
                                title: ['全部', '已选择'],
                                id: 'roleTransferId',//定义索引
                                data: leftData,
                                value:getIds
                            });
                            /**
                             * 其他知识点：
                             * ①数组合并
                             * let newArray=[...DataLeftRoles,...DataRightRoles]
                             * ②单数组去重
                             * let array= uniqueFunc(newArray,"id");
                             * ③取两个数组的差集
                             * let getId = DataRightRoles.map(item=>item.id) 收集id值
                             * 包含返回false   不包含返回true   true代表收集此元素
                             * let newArr = DataLeftRoles.filter(item=>!getId.includes(item.id))
                             * ④创建对象的几种方式
                             * Object构造函数创建  使用对象字面量表示法来创建对象 使用工厂模式创建对象 使用构造函数创建对象
                             * 原型创建对象模式
                             */
                        });
                }
            });
        }

        //单数组去重方法
        function uniqueFunc(arr, uniId){
            const res = new Map();
            return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1));
        }
        //构造函数创建对象
        function valueObject(ld){
            this.value=ld.id;
            this.title=ld.roleName;
            this.disabled=false;
            this.checked='';
        }
        //roleToAdd
        admin.events.roleToAdd = function(){
            //console.log('好')
            //layer.msg($(this).text());
            let getData = transfer.getData('roleTransferId');
            console.log(getData)
        }
        //roleClear
        admin.events.roleClear = function(){
            admin.req('role/getRoleList', function(res){
                let dataLeftRoles=res.LeftRoles;
                let dataRightRoles=res.RightRoles;
                //收集id值
                let getIds = dataRightRoles.map(item=>item.id)
                //重构对象结构
                let leftData=new Array();
                for (let ld of dataLeftRoles) {
                    leftData.push(new valueObject(ld))
                }
                //实例重载
                transfer.reload('roleTransferId', {
                    title: ['全部', '已选择']
                    ,value: getIds
                })
            });

        }

        /* 点击图片放大 */
        $(document).off('click.tbImg').on('click.tbImg', '[tb-img]', function () {
            let imgList = table.cache['userTable'].map(function (d) {
                return {
                    alt: d.nickName,
                    src: d.headUrl || 'assets/images/head.jpg'
                }
            });
            layer.photos({photos: {data: imgList, start: $(this).data('index')}, shade: .1, closeBtn: true});
        });

    });
</script>
</body>
</html>
